layui.config({
    base: '/plugins/module/'
});

layui.use(['form', 'layer', 'laydate', 'table', 'laytpl', 'cstmodules', 'element', 'jquery'], function () {
        var form = layui.form,
            layer = parent.layer === undefined ? layui.layer : top.layer,
            $ = layui.jquery,
            laydate = layui.laydate,
            laytpl = layui.laytpl,
            table = layui.table,
            mymod = layui.cstmodules,
            element = layui.element;
    var stompClient = null;
    //初始化左边方法
    var treeObj = {
        tree: {
            name: null,
            icon: null,
            href: null,
            state: true,
            children: null
        },
        initTreeDate: function () {
            var data =mymod.callBackMethod('/sys/getStaffCollectionInfo', "post", null);
            var tempValue = null;
            if (data != null){
                treeObj.connEcts();
                console.log($.toJSON(data))
                tempValue = data;
            }
            return tempValue;
        },
        colleIsEmpty: function (data) {
            if (data !== null && data && data.length > 0) {
                return true;
            }
            return false;
        },
        objIsEmpty: function (data) {
            if (data !== null && data && data !== '') {
                return true;
            }
            return false;
        },
        getTreeObj:function (data,treeContent) {
            if(data!=null){
                for(var i=0;i<data.length;i++){
                    if(data[i].url==null || data[i].url==""){
                        treeContent=treeContent+"<li class='layui-nav-item'><a data-url="+data[i].url+" data-id="+data[i].menuid+" data-title="+data[i].menuname+" title="+data[i].menuname+" href='#'>";
                        treeContent=treeContent+"<i aria-hidden='true' class='fa "+data[i].icon+"' data-icon='"+data[i].icon+"'> </i><span style='margin-left: 10px'>"+data[i].menuname+"</span>";
                        if(data[i].children!=null){
                            treeContent=treeContent+"<span class='layui-nav-more'></span></a>";
                            treeContent=treeContent+"<dl class='layui-nav-child'>";
                            for(var j=0;j<data[i].children.length;j++){
                                if(data[i].children[j].url!="" &&  data[i].children[j].url!=null){
                                    treeContent=treeContent+"<dd><a data-url="+data[i].children[ j].url+" data-id="+data[i].children[j].menuid+" data-title="+data[i].children[j].menuname+" title="+data[i].children[j].menuname+" href='javascript:;' class='site-left-active' data-type='tabAdd'>";
                                    treeContent=treeContent+"<i style='margin-left: 5px'  class='fa "+data[i].children[j].icon+"' data-icon='"+data[i].children[j].icon+"' aria-hidden='true'></i> <span style='margin-left: 5px'> "+ data[i].children[j].menuname + "</span> </a> </dd>";
                                }else{
                                    var value="";
                                    console.log("递归结果："+this.vectorOjb(data[i].children[j],value));
                                    treeContent=treeContent+this.vectorOjb(data[i].children[j],value,1);
                                }
                            }
                            treeContent=treeContent+"</dl>";
                        }else{
                            treeContent=treeContent+"</a></li>";
                        }
                    }
                }
            }
            return treeContent;
        },
     vectorOjb:function (data,value,index) {
            var flag=index;
            if((data.url=="" || data.url==null) &&  data.children.length>0){
                value=value+"<dd><a data-id='"+data.menuid+"' data-title='"+data.menuname+"'title='"+data.menuname+"' href='#' class='site-left-active' data-type='tabAdd'>";
                value=value+"<i style='margin-left: "+index*5+"px' aria-hidden='true' class='fa "+data.icon+"' data-icon='"+data.icon+"'> </i>";
                value=value+ "<span style='margin-left: 5px'> "+data.menuname+"</span>";
                value=value+"<span class='layui-nav-more'></span></a><dl class='layui-nav-child'>";
                for(var  i=0;i<data.children.length;i++){
                    if(data.children[i].url!=null && data.children[i].url!=""){
                        value=value+"<dd><a data-url='"+data.children[i].url+"' data-id='"+data.children[i].menuid+" data-title='"+data.children[i].menuname+"' title='"+data.children[i].menuname+"' href='javascript:;' class='site-left-active' data-type='tabAdd'>";
                        value=value+"<i style='margin-left: "+(flag+1)*5+"px' class='fa "+data.children[i].icon+"' data-icon='"+data.children[i].icon+"' aria-hidden='true'></i>";
                        value=value+"<span style='margin-left: 5px'> "+data.children[i].menuname+"</span></a>";
                    }else{
                        var temp="";
                        flag=flag+1;
                        value=value+this.vectorOjb(data.children[i],temp,flag);
                    }
                }
                value=value+"</dl></dd>";
            }
            return value;

        },

        //SockJS的一大好处在于提供了浏览器兼容性。即优先使用原生WebSocket，如果浏览器不支持WebSocket，会自动降为轮询的方式。
        connEcts: function () {
            var socket = new SockJS('/websocket-demo');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                // setConnected(true);
                console.log('Connected: ' + frame);//连接服务器成功

                //通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
                stompClient.subscribe('/topic/user', function (greeting) {
                    treeObj.showGreeting(JSON.parse(greeting.body).content);
                });
            });
        },
        //接受SockJS返回的json
        showGreeting: function (message) {
            console.log(message);
            $("#spanInformation1").attr("data-url","/jf/toTestimonialsAudit");
            $("#spanInformation").addClass("layui-badge-dot");
        },
    };
    //初始化头方法
    var obj={
        queryHmenu:function (data) {
                var tempValue=null;
                data.forEach(function(value,index,array){
                    if(value.parentid==null){
                        if(index==0){
                            tempValue="<li class='layui-nav-item layui-this'><a href='#' class='site-left-active'  data-title="+value.menuname+" data-id="+value.menuid+" data-url="+value.url+">"+value.menuname+"</a></li>";
                            tempValue=obj.queryHChmenu(value.menuid,data,tempValue);
                        }else{
                            tempValue=tempValue+"<li class='layui-nav-item'><a href='#' class='site-left-active'  data-title="+value.menuname+" data-id="+value.menuid+" data-url="+value.url+">"+value.menuname+"</a></li>";
                            tempValue=obj.queryHChmenu(value.menuid,data,tempValue);
                        }
                    }
                });
            // alert($.toJSON(tempValue));
            console.info(tempValue);
            $("#headMenu").html(tempValue);
        },
        queryHChmenu:function (menuid,data,tempValue) {
            var flag=0
            data.forEach(function(value,index,array) {
                if(value.parentid==menuid){
                    if(flag==0){
                        tempValue=tempValue.substr(0,tempValue.length-5);
                        tempValue=tempValue+"<dl class='layui-nav-child'><dd><a href='#' class='site-left-active'  data-title="+value.menuname+" data-id="+value.menuid+" data-url="+value.url+">"+value.menuname+"</a></dd></dl></li>"
                        flag=1;
                    }else{
                        tempValue=tempValue.substr(0,tempValue.length-10);
                        tempValue=tempValue+"<dd><a href='#' class='site-left-active'  data-title="+value.menuname+" data-id="+value.menuid+" data-url="+value.url+">"+value.menuname+"</a></dd></dl></li>"
                    }
                }
            });
            return tempValue;
        }
    };
    //调用后台进行初始化左边和头
    var data = treeObj.initTreeDate();
    var treeStr="<ul class='layui-nav layui-nav-tree' lay-shrink='all' id='leftMenuUl'>";
    if (data != null && typeof(data.menuTrees)!='undefined' && data.menuTrees!=null) {
        console.log(treeObj.getTreeObj(data.menuTrees,treeStr)+"</ul>")
        $('#left').html(treeObj.getTreeObj(data.menuTrees,treeStr)+"</ul>");
    }else{
        layer.msg("无核心令牌操作权限,如需请联系管理员配置",{'icon':6});
    };
    if (data != null && typeof(data.htoken)!='undefined' && data.htoken!=null) {
        obj.queryHmenu(data.htoken);
    }
    //监控收缩按钮
    $(".kit-side-fold").off("click").on("click", function () {
        var t = ($(window), $(document));
        var i = t.find("div.kit-side");
        i.hasClass("kit-sided") ? (i.removeClass("kit-sided"), i.find("li.layui-nav-item").removeClass("kit-side-folded"), i.find("dd").removeClass("kit-side-folded"), t.find("div.layui-body").removeClass("kit-body-folded"), t.find("div.layui-footer").removeClass("kit-footer-folded")) : (i.addClass("kit-sided"), i.find("li.layui-nav-item").addClass("kit-side-folded"), i.find("dd").addClass("kit-side-folded"), t.find("div.layui-body").addClass("kit-body-folded"), t.find("div.layui-footer").addClass("kit-footer-folded"));
        element.init();
    });
    // 加载右边结构和左边关联
    var active = {
        tabAdd: function (url, id, name) {
            //新增一个Tab项
            element.tabAdd('seft_table', {
                title: name,
                content: '<iframe data-frameid="' + id + '" frameborder="0" name="content" scrolling="yes" width="100%" src="' + url + '"></iframe>',
                id: id //实际使用一般是规定好的id，这里以时间戳模拟下
            });
            active.CustomRightClick(id);
            active.FrameHeightSet();
        }
        , tabChange: function (id) {
            //切换到指定Tab项
            element.tabChange('seft_table', id); //切换到：用户管理
            $("iframe[data-frameid='" + id + "']").attr("src", $("iframe[data-frameid='" + id + "']").attr("src"))//切换后刷新框架
        }
        , tabDelete: function (id) {
            element.tabDelete("seft_table", id);//删除
        }
        , tabDeleteAll: function (ids) {//删除所有
            $.each(ids, function (i, item) {
                element.tabDelete("seft_table", item);
            })
        },
        CustomRightClick: function (id) {
            //取消右键  rightmenu属性开始是隐藏的 ，当右击的时候显示，左击的时候隐藏
            $('.layui-tab-title li').on('contextmenu', function () {
                return false;
            })
            $('.layui-tab-title,.layui-tab-title li').click(function () {
                $('.rightmenu').hide();
            });
            //桌面点击右击
            $('.layui-tab-title li').on('contextmenu', function (e) {
                var popupmenu = $(".rightmenu");
                popupmenu.find("li").attr("data-id", id); //在右键菜单中的标签绑定id属性

                //判断右侧菜单的位置
                l = ($(document).width() - e.clientX) < popupmenu.width() ? (e.clientX - popupmenu.width()) : e.clientX;
                t = ($(document).height() - e.clientY) < popupmenu.height() ? (e.clientY - popupmenu.height()) : e.clientY;
                popupmenu.css({left: l, top: t}).show(); //进行绝对定位
                //alert("右键菜单")
                return false;
            });
        },
        FrameHeightSet: function () {
            var h = $(window).height() - 152;
            $("iframe").css("height", h + "px");
        },
    };
    $('.site-left-active').on('click', function () {
        var dataid = $(this);
        if(dataid.attr("data-url")!=null && dataid.attr("data-url")!=''){
            //这时会判断右侧.layui-tab-title属性下的有lay-id属性的li的数目，即已经打开的tab项数目
            if ($(".layui-tab-title li[lay-id]").length <= 0) {
                //如果比零小，则直接打开新的tab项
                active.tabAdd(dataid.attr("data-url"), dataid.attr("data-id"), dataid.attr("data-title"));
            } else {
                //否则判断该tab项是否以及存在
                var isData = false; //初始化一个标志，为false说明未打开该tab项 为true则说明已有
                $.each($(".layui-tab-title li[lay-id]"), function () {
                    //如果点击左侧菜单栏所传入的id 在右侧tab项中的lay-id属性可以找到，则说明该tab项已经打开
                    if ($(this).attr("lay-id") == dataid.attr("data-id")) {
                        isData = true;
                    }
                })
                if (isData == false) {
                    //标志为false 新增一个tab项
                    active.tabAdd(dataid.attr("data-url"), dataid.attr("data-id"), dataid.attr("data-title"));
                }
            }
            //最后不管是否新增tab，最后都转到要打开的选项页面上
            active.tabChange(dataid.attr("data-id"));
            active.FrameHeightSet();
            element.init();
        }
    });
    $(".rightmenu li").click(function () {
        //右键菜单中的选项被点击之后，判断type的类型，决定关闭所有还是关闭当前。
        if ($(this).attr("data-type") == "closethis") {
            //如果关闭当前，即根据显示右键菜单时所绑定的id，执行tabDelete
            active.tabDelete($(this).attr("data-id"))
        } else if ($(this).attr("data-type") == "closeall") {
            var tabtitle = $(".layui-tab-title li");
            var ids = new Array();
            $.each(tabtitle, function (i) {
                ids[i] = $(this).attr("lay-id");
            })
            //如果关闭所有 ，即将所有的lay-id放进数组，执行tabDeleteAll
            active.tabDeleteAll(ids);
        }
        $('.rightmenu').hide(); //最后再隐藏右键菜单
        element.init();
    });
    //系统注销
    $("#a_emp_level").bind("click",function () {
        layer.confirm('确定要退出系统吗', {icon: 3, title:'系统注销提示'}, function(index){
                window.location.href="/sys/loginOut";
                layer.close(index);
        })
    });
    //个人信息
    $("#a_emp_info").bind("click",function () {
        var index=layer.open({
            type: 2 //此处以iframe举例
            ,title: '操作员信息'
            ,area: ['600px', '400px']
            ,shade: 0.1
            ,maxmin: true
            ,offset:'auto'
            ,content: '/sys/toChangePwd'
            ,id:'empInfoFrame'
        })
    });

    //安全设置
    $("#a_emp_pwd").bind("click",function () {
        layer.open({
            type: 2 //此处以iframe举例
            ,title: '操作员安全设置'
            ,area: ['600px', '400px']
            ,shade: 0.1
            ,maxmin: true
            ,offset:'auto'
            ,content: '/sys/changePwd'
            ,id:'empset'
        })
    });
    //初始化加载控制台界面
    active.tabAdd("/console/toconsole", 1, "控制台");
    active.tabChange(1);
    active.FrameHeightSet();
    element.init();

    //消息提示删除
    $( "#spanInformation1" ).click(function() {
        $("#spanInformation").removeClass("layui-badge-dot",1);
    });
})